package com.xiaohudie.SGGJUC;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author xiao hu die
 * @Date 2022/3/4 22:43
 * @Version 1.0
 */
class Num2{
    private Integer number=0;
    /**新增重入锁*/
    private Lock lock = new ReentrantLock();
    /**新增condition对象来保证锁的一致性*/
    private Condition condition =lock.newCondition();
    /**加1的方法*/
    public void add() throws InterruptedException {
        try {
            lock.lock();
            while (number == 0) {
                number++;
                condition.signalAll();
                System.out.println(Thread.currentThread().getName() + "number是:" + number);
            }
            condition.await();
        }finally {
            lock.unlock();
        }
        }
    /**加1的方法*/
    public void del() throws InterruptedException {
        lock.lock();
        try {
           while (number==1){
                number--;
                condition.signalAll();
               System.out.println(Thread.currentThread().getName()+"number是:"+number);
           }
           condition.await();
       }
       finally {
           lock.unlock();
       }
    }
}
public class TestCommunication2 {
    public static void main(String[] args) {
        Num2 num2 = new Num2();
        new Thread(() -> {
            for (int i = 0; i <10 ; i++) {
                try {
                    num2.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"AA").start();
    new Thread(() -> {
        for (int i = 0; i <10 ; i++) {
            try {
                num2.del();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    },"BB").start();
    }


}
